package com.wnxy.sddfp.system.service.impl;
import java.math.BigDecimal;
import java.util.UUID;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.wnxy.sddfp.common.exception.Assert;
import com.wnxy.sddfp.common.model.dto.user.UserRegisterDto;
import com.wnxy.sddfp.common.result.enums.impl.BusinessCode;
import com.wnxy.sddfp.system.entity.User;
import com.wnxy.sddfp.system.entity.UserDetail;
import com.wnxy.sddfp.system.mapper.UserMapper;
import com.wnxy.sddfp.system.service.IUserDetailService;
import com.wnxy.sddfp.system.service.IUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * <p>
 * 用户表 服务实现类
 * </p>
 *
 * @author yellow docker
 * @since 2024-11-13
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    @Autowired
    private IUserDetailService iUserDetailService;

    @Override
    public void register(UserRegisterDto userRegisterDto) {

        //校验手机号码  用户名是否存在
        User phoneUser = getOne(Wrappers.lambdaQuery(User.class).eq(User::getPhone, userRegisterDto.getPhone()));
        Assert.error(phoneUser, BusinessCode.PHONE_EXISTED);
        User nameUser = getOne(Wrappers.lambdaQuery(User.class).eq(User::getUserName, userRegisterDto.getUserName()));
        Assert.error(nameUser,BusinessCode.PHONE_EXISTED);

        //保存用户
        User user = new User();
        BeanUtils.copyProperties(userRegisterDto,user);
        user.setUserType("1");
        user.setUserStatus(true);
        save(user);

        //保存用户详情
        UserDetail userDetail = new UserDetail();
        userDetail.setId(user.getId());
        userDetail.setUserName(userRegisterDto.getUserName());
        userDetail.setPhone(userRegisterDto.getPhone());
        userDetail.setBorrowMoney(new BigDecimal("0"));
        userDetail.setUserCode("UC_" + UUID.randomUUID().toString().substring(0,10));
        userDetail.setCardBindStatus(false);

        iUserDetailService.save(userDetail);
    }
}
